package com.zy.gpdemo.service;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.zy.gpdemo.domain.Printer;
import org.springframework.stereotype.Component;

import javax.websocket.OnClose;
import javax.websocket.OnError;
import javax.websocket.OnOpen;
import javax.websocket.Session;
import javax.websocket.server.PathParam;
import javax.websocket.server.ServerEndpoint;

import java.io.IOException;
import java.util.*;
import java.util.concurrent.CopyOnWriteArrayList;

@ServerEndpoint("/websocket/{id}")
@Component
public class WebSocketService {

	private static final List<Session> webSocketMap = new CopyOnWriteArrayList<>();

	@OnOpen
	public void onOpen(@PathParam("id") String id, Session session) {
		webSocketMap.add(session);
		Map<String, List<String>> ips = new HashMap<>();
		ips.put("warehouse", PrinterService.allWarehouse);
		ips.put("ips", PrinterService.allPrinterIp);
		ips.put("stockCode", PrinterService.allStockCode);
		// 初始化界面
		sendMessage(0, "all", JSON.toJSONString(ips));
		for (Printer printer : PrinterService.printers) {
			new Thread(() -> {
				sendMessage(1, printer.getIp(), JSON.toJSONString(printer));
			}).start();
		}
	}

	@OnClose
	public void onClose(@PathParam("id") String id, Session session) {
		webSocketMap.remove(session);
	}

	@OnError
	public void onError(Session session, Throwable throwable) {
		System.out.println("webSocket发生错误！");
	}

	public static void sendMessage(int code, String IP, String message) {
		JSONObject jsonObject = (JSONObject) JSON.parse(message);
		jsonObject.put("code", code);
		jsonObject.put("IP", IP);
		for (Session session : webSocketMap) {
			synchronized (session) {
				try {
					session.getBasicRemote().sendText(jsonObject.toJSONString());
				} catch (IOException e) {
//					System.out.println("websocket连接在发送数据时中断");
				}
			}
		}
	}

}
